<?php

namespace App;

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Intervention\Image\ImageManager;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable  implements JWTSubject
{
    use Notifiable,SoftDeletes;

    protected $table = "t_user";

    protected $appends = ['user_role'];
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = ['password_confirmation'];


    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token','session_key','weixinId'
    ];

    //获取表字段
    public function tableColumns()
    {
        return Schema::getColumnListing($this->getTable());
    }

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
    //[关联]用户角色
    public function role()
    {
        return $this->belongsTo('App\Model\Role','userType','code');
    }
    //[关联]上级
    public function parent()
    {
        return $this->belongsTo('App\User','parent_id','id');
    }
    //[关联]夫集
    public function parents()
    {
        return $this->belongsToMany('App\User','t_user_relation','user_id','parent_id');
    }
    //[关联]子集
    public function childes()
    {
        return $this->belongsToMany('App\User','t_user_relation','parent_id','user_id');
    }
    //[关联]订单分红
    public function bonuses()
    {
        return $this->hasMany('App\Model\OrderBonus','bonus_user_id','id');
    }
    public function createBonuses()
    {
        return $this->hasMany('App\Model\OrderBonus','order_user_id','id');
    }
    public function dealer()
    {
        return $this->belongsTo('App\User','parent_dealer_id','id');

    }

    //用户角色
    public function getUserRoleAttribute()
    {
        return $this->role;
    }

    //更新用户完成的订单总量
    public function updateOrderCount()
    {
        self::updateOrderCountByUserId($this->id);
    }

    //更新用户完成的订单总量
    public static function updateOrderCountByUserId($user_id)
    {
        $c = DB::table('orders')->where('create_user_id','=',$user_id)
            ->whereNull('deleted_at')
            ->whereIn('state',[1,5,6])->count();

        return DB::table('t_user')->where('id','=',$user_id)->update([
            'order_count' => $c
        ]);
    }

    public function updateBonusTotal()
    {
        $this->bonus_total = $this->bonuses()->sum('amount');
        $this->save();
    }
    //更新积分
    public function updatePoint()
    {
        $this->point_total = DB::table('t_user_points')->where('point','>',0)->where('ok','=',1)
            ->where('user_id','=',$this->id)->sum('point');
        $this->point = DB::table('t_user_points')->where('user_id','=',$this->id)->where('ok','=',1)
            ->sum('point');
        return $this->save();
    }

    //更新用户积分
    public static function updateUserPoint($id)
    {
        $user = User::find($id);
        if ($user) {
            return $user->updatePoint();
        }
        return false;
    }
    //通过微信查找用户
    public static function findByWeixinId($weixinId)
    {
        return User::where('weixinId','=',$weixinId)->first();
    }

    //通过邀请码查找用户
    public static function findByInviteCode($invite_code)
    {
        return User::where('invite_code','=',$invite_code)->first();
    }

    public static function getNameById($id)
    {
        $item = DB::table('t_user')->where('id','=',$id)->select('name')->first();
        return $item?$item->name:'';
    }

    //更新用户微信信息
    public function updateUserInfoFromWechat($wechat)
    {

        $sex = [0=>'未知',1=>'男',2=>'女'];

        if(!$this->name && isset($wechat['nickName']) && $wechat['nickName']){
            $this->name = $wechat['nickName'];
        }
        if(!$this->sex && isset($wechat['gender']) && $wechat['gender'] && isset($sex[$wechat['gender']])){
            $this->sex = $sex[$wechat['gender']];
        }
        if(!$this->avatar && isset($wechat['avatarUrl']) && $wechat['avatarUrl']){
            $this->avatar = $wechat['avatarUrl'];
        }
        $this->save();

        return $wechat;
    }

    //登录更新信息
    public function updateFromLogin($request,$newUser=false)
    {
        $parent = false;
        //绑定邀请人
        $invite_code = $request->input('invite_code',false);
        if(!$this->parent_id && $newUser && $invite_code){
            if($parent = self::findByInviteCode($invite_code)){
                $this->parent_id = $parent->id;
                $this->parent_name = $parent->name;
                $this->parent_dealer_id = $parent->is_dealer==1?$parent->id:0;
                $this->active_dealer = $this->parent_dealer_id>0?1:0;
                $this->save();

                self::bindRelation($this->id,$this->parent->id);
            }

        }

        $name = $this->name;

        //用户基础信息
        if ($userInfo = $request->input('userInfo')) {
            try{
                $this->updateUserInfoFromWechat($userInfo);//更新保存信息
            }catch (\Exception $e){
                Log::error($e->getMessage());
            }
        }

        //创建邀请码
        if (!$this->invite_code) {
            $this->createInviteCode();
        }

        if(!$this->invite_url){
            $this->createInviteUrl();
        }

        if (!$name&&$this->mame){
            $this->inviteQRCodeAddName();
        }

    }

    public function beforeSave()
    {
        return true;
    }
    public function afterSave($input=null)
    {
        return true;
    }

    //用户登陆之后
    public function afterLogin()
    {
        return true;
    }
    //创建邀请码
    public function createInviteCode()
    {
        $this->invite_code = strtoupper(base_convert($this->id + 100000000,10,36));
        return $this->save();
    }

    //创建邀请二维码
    public function createInviteUrl()
    {
        //小程序码
        $miniProgram  = app('wechat.mini_program');
        @mkdir(storage_path('app/public/invite'));
        $codePath = $miniProgram->app_code->getUnlimit($this->invite_code)
            ->saveAs(storage_path('app/public/invite'),md5(time().str_random(32)).'.jpg');
        if ($codePath) {
            $this->invite_url = env('QRCODE_URL', asset('/')) . 'storage/invite/' . $codePath;
            $this->save();

            if ($this->name){
                $this->inviteQRCodeAddName();
            }
        }
        return false;
    }

    //判断id用户是否是经销商
    public static function isDealer($id)
    {
        return DB::table('t_user')->where('id','=',$id)->where('tag','=','dealer')->count()>0?true:false;
    }
    //绑定关联
    public static function bindRelation($user_id,$parent_id)
    {
        if (self::createRelation($user_id,$parent_id,1)) {
            $rows = DB::table('t_user_relation')->where('user_id','=',$parent_id)->where('level','<',3)->get();
            foreach ($rows as $row){
                self::createRelation($user_id,$row->parent_id,$row->level+1);
            }
            return true;
        }
        return false;
    }

    //创建关联记录
    public static function createRelation($user_id,$parent_id,$level)
    {
        $c = DB::table('t_user_relation')->where('user_id','=',$user_id)->where('parent_id','=',$parent_id)->count();
        if ($c>0) return false;
        return DB::table('t_user_relation')->insert([
            'user_id' => $user_id,
            'parent_id' => $parent_id,
            'level' => $level,
            'created_at' => date('Y-m-d H:i:s')
        ]);
    }

    //邀请码添加昵称
    public function inviteQRCodeAddName()
    {
        $name = $this->name;
        $file = $this->invite_url;

        $font_path = storage_path('app/template').'/PingFang Regular.ttf';
        $filename = md5($file.time()).'.jpg';
        $savePath = storage_path('app/public/invite').'/'.$filename;


        $manager =  new ImageManager();
        $img = $manager->canvas(500,500,'#FFFFFF');
        $pic = $manager->make($file)->resize(430,430);
        $img->insert($pic,'top-right',35,0);

        if ( mb_strlen($name)>15) $name = mb_substr($name,0,14).'...';
        $w = mb_strlen($name)*26;
        $img->text($name,intval(250-$w*0.5-10),468,function ($font) use ($font_path){
            $font->file($font_path);
            $font->size(26);
            $font->valign('bottom');
            $font->color('#222222');
        });
        $img->save($savePath,100);

        $this->invite_url = env('QRCODE_URL', asset('/')) . 'storage/invite/' . $filename;

        return $this->save();
    }
}
